<template>
  <view class="app-container">
    <image class="background" src="/static/images/background.jpg" mode="aspectFill"></image>

    <view :style="{ marginTop: titleMargin + 'px' }" class="title">{{ title }}</view>

    <view class="swiper-box" v-if="service_list.length > 0">
      <swiper class="swiper" @change="change" ref="swiper" :indicator-dots="false" :autoplay="false" duration="500" :current="swiperIndex">
        <swiper-item v-for="(item, index) in service_list" :key="index" @click="goService">
          <image :src="item.img" mode="aspectFill" class="slide-image"></image>
        </swiper-item>
      </swiper>

      <view class="btn-box" @click="goService">
        <image class="btn" src="/static/images/prev-btn.png" @click.stop="changeSwiper(-1)"></image>
        <image class="btn" src="/static/images/next-btn.png" @click.stop="changeSwiper(1)"></image>
      </view>
    </view>

    <view class="vip-box" v-if="role_id && role_name">
      <view class="wdtg-box" v-if="role_id > 1" @click="goShare">
        <image class="wdtg-icon" src="/static/images/wdtg_icon.png"></image>
        <view class="wdtg">我的推广</view>
      </view>
      <view class="vip">
        当前会员等级：{{ role_name }}
      </view>
    </view>

    <view class="zx-box" v-if="article_list.length > 0">
      <image class="zx-icon" src="/static/images/zx_icon.png"></image>
      <view class="box">
        <view class="zx">最新资讯</view>
        <view class="list-box">
          <view class="list" @click="goArticle(item.id)" v-for="(item, index) in article_list" :key="index">{{ item.title }}</view>
        </view>
      </view>
    </view>

    <view id="mask" v-if="show_login" @click.stop>
      <view class="mask-content" @click.stop>
        <form @submit="formSubmit" class="main-content">
          <view class="title">完善资料</view>
          <button open-type="chooseAvatar" @chooseavatar="getAvatar" class="avatar-btn">
            <image class="btnImg" :src="avatar_path" mode="aspectFill"></image>
          </button>
          <input type="text" :value="avatar" name="avatar" style="display: none">

          <view class="row">
            <view class="left">昵称</view>
            <input type="nickname" @focus="this.showLoginModel = true" @input="this.showLoginModel = true" :value="username" name="nickname" class="input" placeholder="请输入昵称">
          </view>

          <view class="row" style="border-top: none">
            <view class="left">手机号</view>
            <button open-type="getPhoneNumber" :plain="true" @getphonenumber="getPhoneNumber" class="mobile-btn" v-if="!mobile">获取手机号</button>
            <block v-else>
              <input type="number" :value="mobile" name="mobile" style="display: none">
              <view class="input">{{mobile}}</view>
            </block>
          </view>

          <view class="agree-box">
            <button hover-class="none" class="item agree-btn" open-type="agreePrivacyAuthorization">
              <checkbox :checked="is_agree" @click="doAgree" class="checkbox round color" color="#32A4FF" style="background: #FFF"/>
            </button>

            <view class="box">
              阅读并接受
              <text class="text" @click="openPrivacy">{{ privacyContractName }}</text>
            </view>
          </view>

          <input type="text" :value="openid" name="openid" style="display: none">

          <view class="btn-box">
            <button :plain="true" class="button cancel" @click="this.show_login = false">取消</button>
            <button form-type="submit" class="button save">保存</button>
          </view>
        </form>
      </view>
    </view>

    <CustomTabBar :tabList="tabList" :currentTab="currentTab" @change="changeTab"/>
  </view>
</template>

<script>
import http from '@/utils/http'

export default {
  data() {
    return {
      tabList: [],
      currentTab: '',
      service_list: [],
      swiperIndex: 0, // 当前轮播图索引
      title: '',
      titleMargin: 0, // 动态顶部间距
      role_id: 0,
      role_name: '',
      article_list: [],
      show_login: false,
      login_to_url: '',// 登录之后跳转的页面
      privacyContractName: '《喜来啦隐私保护指引》',
      is_agree: false,
      avatar: 0,
      avatar_path: '../../static/images/default_avatar.png',
      mobile: '',
    };
  },

  created() {
    var tab_list = uni.getStorageSync('tab_list');
    if (tab_list) this.tabList = tab_list;

    this.getTabList(); // 获取 TabList
    this.setDynamicMargin(); // 设置动态间距
  },

  onLoad: function () {
    var user_id = uni.getStorageSync('user_id') ? uni.getStorageSync('user_id') : 0;

    this.$http.post('/index/Api/serviceList').then(res => {
      if (res.data.result == 1) {
        this.service_list = res.data.data;
      }
    });

    this.$http.post('/index/Api/articleList', {user_id}).then(res => {
      if (res.data.result == 1) {
        this.article_list = res.data.data;
      }
    })

    if (!user_id) {
      uni.showLoading({
        title: '自动登录中...',
        mask: true
      })

      uni.login({
        success: result => {
          var code = result.code;

          this.$http.post('/index/Api/openidToUserid', {code}).then(res => {
            uni.hideLoading();
            if (res.data.result === 1) {
              var user_id = res.data.data;
              uni.setStorageSync('user_id', user_id)

              this.loadUserCenter(user_id);
            } else {
              this.show_login = true;
            }
          })
        }
      })
    } else {
      this.loadUserCenter(user_id);
    }
  },

  methods: {
    loadUserCenter: function (user_id) {
      var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;
      this.$http.post('/index/Api/userCenter', {user_id, scene_user_id}).then(res => {
        if (res.data.result == 1) {
          // 存储认证状态
          uni.setStorageSync('rz_status', res.data.data.rz_status)

          this.role_id = res.data.data.role_id;
          this.role_name = res.data.data.role_name;
          if (res.data.data.up_user_id > 0) uni.removeStorageSync('scene_user_id');
        }
      })
    },

    openPrivacy: function () {
      uni.openPrivacyContract()
    },

    getAvatar: function (e) {
      var {avatarUrl} = e.detail;

      uni.uploadFile({
        url: http.config.baseURL + '/Upload/UploadFile/uniUploadPicture', //服务端图片上传接口地址
        filePath: avatarUrl,
        name: 'download',
        formData: {},
        success: res => {
          res = JSON.parse(res.data)
          if (res.result === 1) {
            uni.showToast({
              title: '上传头像成功'
            })
            this.showLoginModel = true;
            this.avatar_path = res.data.path;
            this.avatar = res.data.id;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          }, 500)
        }
      })
    },

    doAgree: function () {
      this.is_agree = !this.is_agree;
    },

    getPhoneNumber: function (e){
      var code = e.detail.code;
      this.$http.post('/index/Api/getMobile', {code}).then(res => {
        if (res.data.result === 1) {
          this.mobile = res.data.data
        }else{
          this.$common.doErrorResult(res)
        }
      })
    },


    formSubmit: function (e) {
      var formData = e.detail.value,
        timestamp = Date.parse(new Date()),//该值除以1000就是当前的时间戳,
        sync_timestamp = uni.getStorageSync('timestamp') ? uni.getStorageSync('timestamp') : 0,//获取时间戳缓存,
        now_timestamp = timestamp / 1000,
        long_time = now_timestamp - sync_timestamp;//距离上次点击按钮经过的时长（秒）,

      if (!this.is_agree) {
        uni.showToast({
          title: '请阅读并勾选小程序隐私保护指引',
          icon: 'none'
        })
        return;
      }

      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      if (long_time > 3) {
        //将当前时间戳存为缓存
        uni.setStorageSync('timestamp', timestamp / 1000);

        uni.login({
          success: result => {
            var code = result.code;

            this.$http.post('/index/Api/getOpenid', {code}).then(res => {
              if (res.data.result === 1) {
                formData.openid = res.data.data;

                this.$http.post('/Index/Api/login', formData).then(res => {
                  uni.removeStorageSync('timestamp');
                  uni.hideLoading();

                  if (res.data.result === 1) {
                    var user_id = res.data.data;
                    uni.setStorageSync('user_id', user_id)

                    this.show_login = false;

                    this.loadUserCenter(user_id)
                  } else {
                    this.$common.doErrorResult(res);
                  }
                })
              } else {
                this.$common.doErrorResult(res);
              }
            })
          }
        })
      }
    },

    getTabList() {
      this.$http.post('/index/Api/getTabbar').then(res => {
        if (JSON.stringify(this.tabList) !== JSON.stringify(res.data.data)) {
          uni.setStorageSync('tab_list', res.data.data);
          this.tabList = res.data.data;
        }
        // 默认选中的 Tab
        this.currentTab = this.tabList[1].path;
        this.title = this.tabList[1].text;
      });
    },
    changeTab(path) {
      this.currentTab = path;
      uni.redirectTo({url: path}); // 切换到指定的页面
    },
    setDynamicMargin() {
      const windowInfo = uni.getWindowInfo();
      this.titleMargin = windowInfo.statusBarHeight + 10; // 直接使用状态栏高度
    },

    change: function (e) {
      this.swiperIndex = e.detail.current;
    },

    changeSwiper(direction) {
      // 计算新的索引
      const newIndex = this.swiperIndex + direction;
      if (newIndex >= 0 && newIndex < this.service_list.length) {
        this.swiperIndex = newIndex; // 更新索引
      }
    },

    goService: function () {
      let id = this.service_list[this.swiperIndex].id;
      uni.navigateTo({
        url: '/pages/service_detail/service_detail?id=' + id
      })
    },

    goArticle: function (id) {
      uni.navigateTo({
        url: '/pages/article/article?id=' + id
      })
    },

    goShare: function () {
      uni.navigateTo({
        url: '/pages/share/share'
      })
    },
  },
}
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 10rpx;

  button{
    border: none;
    padding: 0;
    margin: 0;
  }

  .title {
    font-size: 40rpx;
    text-align: center;
  }

  .swiper-box {
    display: flex;
    width: 100%;
    position: relative;
    justify-content: center;

    .swiper {
      width: 91%;
      height: 340rpx; /* 设置轮播图高度 */
      border-radius: 40rpx; /* 设置圆角 */
      overflow: hidden; /* 确保子元素超出部分被隐藏 */
      margin-top: 40rpx;
      position: relative;

      .slide-image {
        width: 100%;
        height: 100%;
      }
    }

    .btn-box {
      position: absolute;
      top: calc(50% - 20rpx);
      width: 100%;
      height: 50rpx;
      z-index: 1;
      display: flex;
      justify-content: space-between;

      .btn {
        width: 60rpx;
        height: 60rpx;
      }
    }
  }

  .vip-box {
    width: 91%;
    height: 260rpx;
    background: #FCD4CE;
    margin: 40rpx 0;
    border-radius: 20rpx;
    position: relative;
    display: flex;
    align-items: center;

    .wdtg-box {
      position: absolute;
      top: 20rpx;
      right: 20rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .wdtg-icon {
        width: 40rpx;
        height: 50rpx;
      }

      .wdtg {
        font-size: 42rpx;
        margin-left: 20rpx;
        color: #F30E0E;
      }
    }

    .vip {
      font-size: 40rpx;
      font-weight: bold;
      margin-left: 40rpx;
    }

  }

  .zx-box {
    width: calc(91% - 60rpx);
    min-height: 260rpx;
    background: #fff;
    margin: 40rpx 0;
    border-radius: 20rpx;
    padding: 30rpx 30rpx 60rpx 30rpx;
    display: flex;

    .zx-icon {
      width: 38rpx;
      height: 44rpx;
      flex-shrink: 0; // 防止被挤压
    }

    .box {
      display: flex;
      flex-direction: column;
      margin-left: 20rpx;

      .zx {
        font-size: 42rpx;
        color: #F30E0E;
      }

      .list-box {
        margin-top: 40rpx;

        .list {
          margin-top: 30rpx;
          font-size: 32rpx;

          &:first-child {
            margin-top: 0;
          }
        }
      }
    }

  }
}
</style>
